/**
 * Created by Jack Xue on 20101115
 */
package org.code.jack.jweberp.core;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.code.jack.jweberp.web.BaseAction;

/**
 *  框架核心引擎(辅助struts工具)
 */
@SuppressWarnings("unchecked")
public class FrameworkEngine {
	private static final Logger logger = Logger.getLogger(FrameworkEngine.class);
	private static Properties properties = new Properties();
	static {
		try {
			properties.load(BaseAction.class.getClassLoader().getResourceAsStream("application.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据request创建一个form对象
	 * 
	 * @param request
	 * @param formName
	 * @return 封装了用户数据的Form
	 */
	@SuppressWarnings("rawtypes")
	public static WebForm creatWebForm(HttpServletRequest request) {
		Map textElement = new HashMap();
		Map fileElement = new HashMap();
		String contentType = request.getContentType();
		String reMethod = request.getMethod();
		// 二进制上传文件
		if ((contentType != null) && (contentType.startsWith("multipart/form-data")) && (reMethod.equalsIgnoreCase("post"))) {
			List reqPars = null;
			try {
				reqPars = parseFileUpload(request).parseRequest(request);
				for (int i = 0; i < reqPars.size(); i++) {
					FileItem it = (FileItem) reqPars.get(i);
					if (it.isFormField()) {
						textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// 文本字段需要转码
					} else {
						fileElement.put(it.getFieldName(), it);// 文件不需要转码
					}
				}
			} catch (Exception e) {
				logger.error(e);
			}
			// XML形式
		} else if ((contentType != null) && contentType.equals("text/xml")) {
			StringBuffer buffer = new StringBuffer();
			try {
				String s = request.getReader().readLine();
				while (s != null) {
					buffer.append(s + "\n");
					s = request.getReader().readLine();
				}
			} catch (Exception e) {
				logger.error(e);
			}
			textElement.put("xml", buffer.toString());
		} else {
			// 传统方式
			textElement = request2map(request);
		}
		logger.debug("表单数据处理完毕！数据存放在WebForm对象中");
		WebForm wf = new WebForm();
		if (wf != null) {
			wf.setFileElement(fileElement);
			wf.setTextElement(textElement);
		}
		return wf;
	}

	/**
	 * 一个通用的reuqest数据到map的转换
	 * 
	 * @param request
	 * @return Map
	 */
	@SuppressWarnings("rawtypes")
	public static Map request2map(HttpServletRequest request) {
		Map map = new HashMap();
		Enumeration s = request.getParameterNames();
		while (s.hasMoreElements()) {
			String name = (String) s.nextElement();
			// eliminateScript((String)request.getParameter(name)));//消除参数中的特殊字符
			// 属性名对应的属性值很可能是一个数组,如多选操作
			String[] vs = request.getParameterValues(name);
			if ("".equals(vs) || vs.length < 1) {
				map.put(name, null);
			} else {
				map.put(name, vs.length > 1 ? vs : vs[0]);// vs.length>1表明视图层传递上传的是多个属性值
			}
		}
		return map;
	}

	/**
	 * 装配上传文件
	 */
	public static ServletFileUpload parseFileUpload(HttpServletRequest request) {
		File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
		if (!file.exists()) {
			file.getParentFile().mkdirs();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(new Integer(properties.getProperty("uploadFile.SizeThreshold")));// 上传文件缓存值
		factory.setRepository(file);
		ServletFileUpload sf = new ServletFileUpload(factory);
		sf.setSizeMax(new Long(properties.getProperty("uploadFile.SizeMax")));
		sf.setHeaderEncoding(request.getCharacterEncoding());
		return sf;
	}
}
